# -*- coding: utf-8 -*-
"""
@Time : 2023/6/11 19:26
@Author : Gremore
@File : plan_api
@Des: 
"""
from tsim.routers.plan.request_model import CreatePlanBody, UpdatePlanBody, DeletePlanBody
from tsim.commons.responses.response_model import ResponseDto, ListResponseDto
from tsim.models import Session
from tsim.models.plan import PlanTab
from tsim.core.Response import success, fail
from fastapi import Request, Query, APIRouter, Security, File, UploadFile
from tsim.commons.utils import typetransfer


def plan_create(body: CreatePlanBody):
    session = Session()
    model = PlanTab

    plan = model(body)
    session.add(plan)
    session.commit()  # 最后需要调用commit()方法提交事务

    return ResponseDto(msg="添加成功")


def plan_list(page: int = 1, limit: int = 10, search: str = None):
    session = Session()
    model = PlanTab
    # like 比较特殊，必须f"%{search}%" if search else None
    if search is None:
        result = session.query(model).all()
    else:
        result = session.query(model).filter(model.title == search).first()
    print("result:", result)
    return success(data=result, msg='查询成功')


plan_router = APIRouter()


@plan_router.post("/update", summary="计划修改")
async def plan_update(body: UpdatePlanBody):
    """
    更新用户信息
    :param body:
    :return:
    """
    session = Session()
    model = PlanTab

    check = session.query(model).filter(model.id == body.id).first()
    if not check:
        return fail(msg="id不存在")
    if check.title == body.title:
        return fail(msg=f"计划名{check.title}已存在")


    print("请求修改：", typetransfer.convert_to_dict(body))
    print("请求修改：", body)
    session.query(model).filter(model.id == body.id).update(typetransfer.convert_to_dict(body))
    session.commit()
    return success(msg="更新成功!")


@plan_router.delete("/delete", summary="计划删除")
async def plan_del(body: DeletePlanBody):
    """
    删除
    :param body
    :return:
    """
    print("请求修改：", body)
    session = Session()
    model = PlanTab
    result = session.query(model).filter(model.id == body.id).first()
    session.delete(result)  # 删除数据
    session.commit()  # 提交事务

    return success(msg="删除成功")

